#!/usr/bin/env python3
import argparse
import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from src.counter import TextCounter

def main():
    """主函数：wc.exe风格的命令行接口"""
    parser = argparse.ArgumentParser(
        description='文本计数统计工具 - wc.exe风格',
        prog='wc.exe',
        usage='wc.exe [参数] [文件名]'
    )
    
    # 添加参数（按照wc.exe风格）
    parser.add_argument(
        '-c', 
        action='store_true',
        help='统计字符数'
    )
    
    parser.add_argument(
        '-w',
        action='store_true', 
        help='统计单词数'
    )
    
    parser.add_argument(
        '-s',
        action='store_true',
        help='统计句子数'
    )
    
    parser.add_argument(
        '-l',
        action='store_true',
        help='统计行数信息'
    )
    
    parser.add_argument(
        '-a',
        action='store_true', 
        help='显示所有统计信息'
    )
    
    parser.add_argument(
        'filename',
        help='要统计的文本文件路径'
    )
    
    # 解析参数
    args = parser.parse_args()
    
    try:
        # 创建计数器实例
        counter = TextCounter(args.filename)
        
        # 根据参数执行相应操作
        if args.c:
            print(f"字符数: {counter.count_chars()}")
        
        elif args.w:
            print(f"单词数: {counter.count_words()}")
        
        elif args.s:
            print(f"句子数: {counter.count_sentences()}")
        
        elif args.l:
            total, empty, comments = counter.count_lines()
            code_lines = total - empty - comments
            print(f"总行数: {total}")
            print(f"空行数: {empty}") 
            print(f"注释行: {comments}")
            print(f"代码行: {code_lines}")
        
        elif args.a:
            stats = counter.get_all_stats()
            print("=== 文本统计结果 ===")
            print(f"字符数: {stats['characters']}")
            print(f"单词数: {stats['words']}")
            print(f"句子数: {stats['sentences']}")
            print(f"总行数: {stats['total_lines']}")
            print(f"空行数: {stats['empty_lines']}")
            print(f"注释行: {stats['comment_lines']}")
            print(f"代码行: {stats['code_lines']}")
        
        else:
            # 如果没有指定具体参数，默认显示基础信息
            print("=== 文本统计结果 ===")
            print(f"字符数: {counter.count_chars()}")
            print(f"单词数: {counter.count_words()}")
            print(f"句子数: {counter.count_sentences()}")
    
    except FileNotFoundError as e:
        print(f"错误: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"发生错误: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
    class TextCounter:
    """文本计数器类，提供各种文本统计功能"""
    
    def __init__(self, filename):
        self.filename = filename
        self.content = self._read_file()
    
    def _read_file(self):
        """读取文件内容"""
        try:
            with open(self.filename, 'r', encoding='utf-8') as file:
                return file.read()
        except FileNotFoundError:
            raise FileNotFoundError(f"文件 '{self.filename}' 未找到")
        except Exception as e:
            raise Exception(f"读取文件时出错: {str(e)}")
    
    def count_chars(self):
        """统计字符数（包括空格和换行符）"""
        return len(self.content)
    
    def count_words(self):
        """统计单词数（基于空格分隔）"""
        words = self.content.split()
        return len(words)
    
    def count_sentences(self):
        """统计句子数（基于句号、问号、感叹号分隔）"""
        count = 0
        for char in self.content:
            if char in '.!?':
                count += 1
        return count
    
    def count_lines(self):
        """
        统计代码行相关信息
        返回: (总行数, 空行数, 注释行数)
        """
        lines = self.content.split('\n')
        total_lines = len(lines)
        empty_lines = 0
        comment_lines = 0
        
        for line in lines:
            stripped_line = line.strip()
            # 统计空行
            if not stripped_line:
                empty_lines += 1
            # 统计注释行（以#开头）
            elif stripped_line.startswith('#'):
                comment_lines += 1
        
        return total_lines, empty_lines, comment_lines
    
    def get_all_stats(self):
        """获取所有统计信息"""
        total_lines, empty_lines, comment_lines = self.count_lines()
        
        return {
            'characters': self.count_chars(),
            'words': self.count_words(),
            'sentences': self.count_sentences(),
            'total_lines': total_lines,
            'empty_lines': empty_lines,
            'comment_lines': comment_lines,
            'code_lines': total_lines - empty_lines - comment_lines
        }